<template>
  <div class="doodle-view" :style="{width: 'auto'}">

    <div class="doodle-view-content" v-loading='loading' :style="{height: height+'px'}">
      <canvas class="doodle-canvas" :class="isClear && 'clear'" ref="doodleCanvas" :width="loading ? 0 : imgWidth" :height="loading ? 0 : imgHeight" :style="{opacity: markOpacity}" />
      <img class="doodle-img" :src="src" :width="loading ? 0 : imgWidth" :height="loading ? 0 : imgHeight" @load="resetZoom" />
    </div>

  </div>
</template>

<script>
/** 点击图片选中区域 */
/* eslint-disable */
import maskJson from "../../../temporaryData/mask.json";
import WebRequest from '@/unit/request.js'
export default {
  name: 'Select',
  props: {
    // 图片url
    src: {
      type: String,
      default: ''
    },
    // 宽度
    width: {
      type: Number,
      default: 500
    },
    // 高度
    height: {
      type: Number,
      default: 300
    },
    // 遮罩透明度
    markOpacity: {
      type: Number,
      default: 0.6
    },
  },
  data () {
    return {
      history: [],          // 历史记录
      historyIndex: -1,     // 历史记录下标
      dragging: false,      // 是否绘制中
      isClear: false,       // 是否为擦除模式
      imgWidth: 500,        // 图像原始宽度，同时作用于画布
      imgHeight: 300,       // 图像原始高度，同时作用于画布
      zoom: 1,              // 缩放比例
      markImageOriginal: null,      // 原始遮罩图：base64
      markImage: null,      // 遮罩图：base64
      loading: false,       // 图片是否加载中

      canvas: null,
      ctx: null,
      canvasPos: null,
      shadowCanvas: null,
      shadowCtx: null,
      shadowHistory: [],

      savePants: null,
    }
  },
  created() {
    setTimeout(() => {
      this.init()
    }, 500)
  },
  watch: {
    src: {
      handler() {
        this.resetAll()
      },
      immediate: true
    },
  },
  methods: {
    /** 重置 */
    reset() {
      console.log('select')
    },
    /** 初始化 */
    async init() {
      this.canvas = this.$refs['doodleCanvas']
      this.ctx = this.canvas.getContext('2d',{willReadFrequently:true})
      this.canvasPos = this.canvas.getBoundingClientRect()

      // try {
      //   await WebRequest.ALi.InteractiveFullSegmentation({
      //     imageUrl: 'https://picture.2beauti.com/prometheus/20240386/1711435886588.png'
      //   })
      // } catch (error) {
      //   console.log('错误信息',error)
      // }

    },
    /** 重置比例 */
    resetZoom(e) {
      this.loading = true
      let img = new Image()
      img.src = this.src
      img.onload = (e2) => {
        let w = e2.currentTarget.width
        let h = e2.currentTarget.height
        // 计算缩放比例(原图/指定尺寸)
        this.shadowCanvas = document.createElement('canvas')
        this.shadowCtx = this.shadowCanvas.getContext('2d',{willReadFrequently:true})
        this.shadowCanvas.width = w
        this.shadowCanvas.height = h
        // 计算纵横比
        let width = this.width
        let height = parseInt(h * (this.width / w))
        if (w >= h) {
          if (height > this.height) {
            width = parseInt(w * (this.height / h))
            height = this.height
          }
          this.zoom = w / width
        } else {
          width = parseInt(w * (this.height / h))
          height = this.height
          if (width > this.width) {
            width = this.width
            height = parseInt(h * (this.width / w))
          }
          this.zoom = h / height
        }
        this.imgWidth = width
        this.imgHeight = height
        this.loading = false
      }
    },
    /** 重置所有设置 */
    async resetAll() {
      // console.log('变更图片地址：', this.src)

      // try {
      //   let data = await WebRequest.ComfyUi.UploadImage({ imageUrl: this.src })
      //   if (data.status == 200) {
      //     let name = data.data.name
      //     let jobData = await WebRequest.ALi.InteractiveFullSegmentation({ imageUrl: name})
      //     if (jobData.status == 200) {
      //       let jobId = jobData.data.RequestId
      //       let called = true
      //       let call = setInterval(async () => {
      //         if(called){
      //           called = false
      //           try {
      //             let resData = await WebRequest.ALi.getJobResult({ jobId: '7F6B67D6-67BB-5D97-BF59-E96C58669661' })
      //             if (resData.status == 200) {
      //               console.log('jobData:', resData.data)
      //               clearInterval(call)
      //             }
      //           } catch (error) {
                  
      //           }
      //         } else {
      //           clearInterval(call)
      //         }
      //       })
      //     } else {
      //       this.$message({ type: 'error', message: '获取任务错误' })
      //     }
      //   } else {
      //     console.log('图片上传失败')
      //   }
      // } catch (error) {
      //   console.log(error)
      // }

      // 重新读取图片和比例
      this.resetZoom()
    },
    /** 变更图片 */
    onChangeImage() {
      this.resetAll()
    },
    
    getCursorPosition(e) {
      return { x: e.offsetX, y: e.offsetY }
      // return {
      //   x: e.clientX - this.canvasPos.left,
      //   y: e.clientY - this.canvasPos.top
      // }
    },

    /** 输出遮罩 */
    output() {
      let w = this.shadowCanvas.width
      let h = this.shadowCanvas.height
      let imgData = this.shadowCtx.getImageData(0, 0, w, h)
      let data = imgData.data
      for (let i2 = 0; i2 < data.length; i2 += 4) {
        if (data[i2 + 3] > 0) {
          data[i2 + 0] = data[i2 + 1] = data[i2 + 2] = 255
        }
      }
      let canvas = document.createElement('canvas'),
          canvas2 = document.createElement('canvas'),
          img = new Image()
      canvas2.width = canvas.width = w
      canvas2.height = canvas.height = h
      let ctx = canvas.getContext('2d',{willReadFrequently:true}),
          ctx2 = canvas2.getContext('2d',{willReadFrequently:true})
      ctx.putImageData(imgData, 0, 0)
      img.src = canvas.toDataURL()
      img.onload = () => {
        ctx2.fillStyle = '#000000'
        ctx2.fillRect(0, 0, w, h)
        ctx2.drawImage(img, 0, 0)
        this.markImageOriginal = this.shadowCanvas.toDataURL()
        this.markImage = canvas2.toDataURL()
        canvas.remove()
        canvas2.remove()
        img.remove()
        this.$emit('comfirm', {original: this.markImageOriginal, mark: this.markImage})
      }
    },

    /** 选择笔触 */
    selectLineWidth(e) {
      let width = e.currentTarget.dataset.width
      this.currentLineWidth = width
    }
  }
}
</script>
<style src="./index.scss" lang="scss"></style>
<style lang="scss" scoped>
.doodle-view-content {
  margin-left: 0;
}
</style>
